package com.example.tabbar.adapter

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.tabbar.databinding.DropdownItemBinding

class SpinnerAdapters(private val items: List<String>, private val listener: OnItemClickListener) :
    RecyclerView.Adapter<SpinnerAdapters.ViewHolder>() {
    private var selectedPosition = -1

    interface OnItemClickListener {
        fun onItemClick(position: Int)
    }


    fun setSelectedPosition(position: Int) {
        if (selectedPosition == position) return

        val previousPosition = selectedPosition
        selectedPosition = position

        if (previousPosition >= 0 && previousPosition < itemCount) {
            notifyItemChanged(previousPosition) // 通知旧位置更新
        }

        if (selectedPosition >= 0 && selectedPosition < itemCount) {
            notifyItemChanged(selectedPosition) // 通知新位置更新
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding =
            DropdownItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = items[position]
        holder.textView.text = item
        holder.textView.isSelected = position == selectedPosition
        if (position == selectedPosition) {
            holder.textView.setTextColor(Color.WHITE)
        }

        holder.itemView.setOnClickListener { v: View? ->
            if (selectedPosition != position) {
                setSelectedPosition(position)
                listener.onItemClick(position)
            }
        }
    }

    override fun getItemCount(): Int {
        return items.size
    }

    inner class ViewHolder(binding: DropdownItemBinding) :
        RecyclerView.ViewHolder(binding.root) {
        var textView: TextView = binding.itemText
    }
}
